package com.snopy.jvm;

import java.io.*;
import java.security.ProtectionDomain;

/**
 * @author snopy
 * @version 1.0.0
 * @classname CustomClassLoader
 * @description
 * @email 77912204@qq.com
 * @date 2022/08/21 22:59
 */
public class CustomClassLoader extends ClassLoader{

    private String path;
    public CustomClassLoader(String path){
        this.path = path;
    }

    public CustomClassLoader(ClassLoader parent, String path) {
        super(parent);
        this.path = path;
    }

    @Override
    public Class<?> findClass(String name) throws ClassNotFoundException {
        BufferedInputStream reader = null;
        ByteArrayOutputStream outputStream = null;
        try {
            reader = new BufferedInputStream(new FileInputStream(path+name+".class"));
            outputStream = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int c;
            while ((c = reader.read(bytes))!=-1){
                outputStream.write(bytes,0,c);
            }
            outputStream.flush();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if (reader!=null){
                try {
                    reader.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return defineClass(null, outputStream.toByteArray(), 0, outputStream.toByteArray().length);
    }

   /* @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        System.out.println("findClass------------");
        return super.findClass(name);
    }*/
}
